package com.ynet.eq.common.entity;

import com.baomidou.mybatisplus.annotation.TableField;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.google.common.collect.Lists;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Data
@NoArgsConstructor
@EqualsAndHashCode(callSuper = false)
public class BaseTree extends BaseEntity implements java.io.Serializable {
    private static final long serialVersionUID = 751680820752568717L;


    private Long parentId;
    @TableField(exist = false)
    @JsonInclude(JsonInclude.Include.NON_EMPTY)
    private List<? super BaseTree> children = Lists.newArrayList();

    public static <T extends BaseTree> List<T> listToTree(List<T> list) {
        Set<Long> parentIdSet = list.stream().map(BaseTree::getParentId).collect(Collectors.toSet());
        Set<Long> idSet = list.stream().map(BaseTree::getId).collect(Collectors.toSet());
        parentIdSet.removeAll(idSet);
        //用递归找子。
        return list.stream()
                .filter(tree -> parentIdSet.contains(tree.getParentId()))
                .map(tree -> findChildren(tree, list))
                .collect(Collectors.toList());
    }

    private static <T extends BaseTree> T findChildren(T tree, List<T> list) {
        list.stream()
                .filter(node -> node.getParentId().equals(tree.getId()))
                .map(node -> findChildren(node, list))
                .forEachOrdered(children -> tree.getChildren().add(children));
        return tree;
    }

}
